package com.company.bookstore.validator.user_admin_module;

import com.company.bookstore.exception.user_admin_module.CustomException;
import com.company.bookstore.qo.user_admin_module.UserQo;
import com.company.bookstore.service.user_admin_module.UserService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * UserQoRegisterValidator
 *
 * @blame Android Team
 */
@Component
public class UserQoRegisterValidator  extends AbstractValidatorHandler implements InitializingBean {

    @Resource
    UserService userService;
    static final Pattern USERNAME_PATTERN = Pattern.compile("\\w{8,20}");

    static  final   Pattern PASSWORD_PATTERN = Pattern.compile("[\\w|\\pP]{8,20}");
    @Override
    public boolean doValidator(Object object) throws CustomException {
        UserQo userQo = (UserQo)object;
        boolean hasPassword =  userQo.getPassword()!=null;
        boolean hasUsername =  userQo.getUsername()!=null;
        Matcher correctUsername;
        boolean hasCorrectUsername;
        Matcher correctPassword;
        boolean hasCorrectPassword;
        if (hasUsername){


            correctUsername = USERNAME_PATTERN.matcher(userQo.getUsername());
            hasCorrectUsername = correctUsername.matches();
            if (!hasCorrectUsername){
                throw  new CustomException("账号账户名格式不正确，要求8-20位字母，数字，不能含有标点符号",403);
            }
            if (userService.loadUserByUsername(userQo.getUsername())!=null){
                throw   new CustomException("该账户已存在",403);
            }
        }else {
            throw  new CustomException("账号名不能为空",403);
        }
        if (hasPassword){
            correctPassword = PASSWORD_PATTERN.matcher(userQo.getPassword());
            hasCorrectPassword = correctPassword.matches();
            if (!hasCorrectPassword){
                throw  new CustomException("账号密码格式不正确，要求8-20位字母，数字，可含有标点符号",403);
            }
        }else {
            throw  new CustomException("账号密码不能为空",403);
        }
        boolean containIllegalParams = userQo.getDeleted()!=null || userQo.getEnable()!=null
                || userQo.getId() != null || userQo.getEmail() !=null || userQo.getPhone()!=null
                || userQo.getTempAdd()!=null;
        if (containIllegalParams){
            throw  new CustomException("参数格式，数量不正确",403);
        }
        return true;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        ValidatorFactory.register(this.getClass().getName(),this);
    }
}
